package com.hd.trans.widgets.filter;

import android.text.InputFilter;
import android.text.Spanned;

import com.hd.trans.common.interf.FilterMaxCallback;


/**
 * 
 * @ClassName: EditLenInputFilter
 * @Description: 编辑框 长度过滤
 * @author yangHuang
 * @date 2015-11-11
 *
 */
public class EditLenInputFilter implements InputFilter {

	private FilterMaxCallback mCallback;

		public EditLenInputFilter(int max) {
			mMax = max;
		}
		public EditLenInputFilter(int max,FilterMaxCallback callback) {
			mMax = max;
			mCallback = callback;
		}

		public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
			
			int keep = mMax - (dest.length() - (dend - dstart));

			if (keep <= 0) {

				if(mCallback!=null){
					mCallback.onFilterNot(mMax);
				}

				return "";
			} else if (keep >= end - start) {
				return null; // keep original
			} else {
				keep += start;
				if (Character.isHighSurrogate(source.charAt(keep - 1))) {
					--keep;
					if (keep == start) {
						return "";
					}
				}
				return source.subSequence(start, keep);
			}
		}

		private int mMax;

	}